﻿using StudentLive.Common;
using StudentLive.DataModel;
using StudentLive.InnerPages;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Windows.ApplicationModel.Activation;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.Storage;
using Windows.UI.Core;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;

// The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=234238

namespace StudentLive
{
    /// <summary>
    /// An empty page that can be used on its own or navigated to within a Frame.
    /// </summary>
    public sealed partial class ExtendedSplash
    {

        public static LiveDataSource DataSource { get; private set; }

        internal Rect splashImageRect; // Rect to store splash screen image coordinates.
        internal bool dismissed = false; // Variable to track splash screen dismissal status.
        internal Frame rootFrame;

        private SplashScreen splash; // Variable to hold the splash screen object.

        public ExtendedSplash(SplashScreen splashscreen, bool loadState)
        {
            InitializeComponent();
            // Listen for window resize events to reposition the extended splash screen image accordingly.
            // This is important to ensure that the extended splash screen is formatted properly in response to snapping, unsnapping, rotation, etc...
            Window.Current.SizeChanged += new WindowSizeChangedEventHandler(ExtendedSplash_OnResize);

            splash = splashscreen;

            if (splash != null)
            {
                // Register an event handler to be executed when the splash screen has been dismissed.
                splash.Dismissed += new TypedEventHandler<SplashScreen, Object>(DismissedEventHandler);

                // Retrieve the window coordinates of the splash screen image.
                splashImageRect = splash.ImageLocation;
                PositionImage();
            }

            // Create a Frame to act as the navigation context 
            rootFrame = new Frame();

            // Restore the saved session state if necessary
            RestoreStateAsync(loadState);

        }

        async void RestoreStateAsync(bool loadState)
        {
            if (loadState)
                await SuspensionManager.RestoreAsync();

            await PerformSetupTasks();
            // Normally you should start the time consuming task asynchronously here and 
            // dismiss the extended splash screen in the completed handler of that task
            // This sample dismisses extended splash screen  in the handler for "Learn More" button for demonstration
        }

        // Position the extended splash screen image in the same location as the system splash screen image.
        void PositionImage()
        {
            extendedSplashImage.SetValue(Canvas.LeftProperty, splashImageRect.X);
            extendedSplashImage.SetValue(Canvas.TopProperty, splashImageRect.Y);
            extendedSplashImage.Height = splashImageRect.Height;
            extendedSplashImage.Width = splashImageRect.Width;

            // Position the extended splash screen's progress ring.
            this.ProgressRing.SetValue(Canvas.TopProperty, splash.ImageLocation.Y + splash.ImageLocation.Height + 32);
            this.ProgressRing.SetValue(Canvas.LeftProperty, splash.ImageLocation.X + (splash.ImageLocation.Width / 2) - 15);
        }

        void ExtendedSplash_OnResize(Object sender, WindowSizeChangedEventArgs e)
        {
            // Safely update the extended splash screen image coordinates. This function will be fired in response to snapping, unsnapping, rotation, etc...
            if (splash != null)
            {
                // Update the coordinates of the splash screen image.
                splashImageRect = splash.ImageLocation;
                //PositionImage();
            }
        }

        // Include code to be executed when the system has transitioned from the splash screen to the extended splash screen (application's first view).
        void DismissedEventHandler(SplashScreen sender, object e)
        {
            dismissed = true;

            // Place the frame in the current Window
        }

        async Task PerformSetupTasks()
        {
            // Begin additional loading tasks here…
            //...
            var localSettings = Windows.Storage.ApplicationData.Current.LocalSettings;
            Object value = localSettings.Values[Constants.IsDatabaseInstalled];

            if (value == null || !(bool)value)
            {
                // No data
                Debug.WriteLine("Database is not installed, will install it now");

                await InstallDatabase();

                Debug.WriteLine("Database is now installed");
            }
            else
            {
                // Access data in value
                Debug.WriteLine("Database was already installed, no need to copy..");
            }
            // Tear down the extended splash screen after all operations are complete.

            DataSource = LiveDataSource.DataSource;

            await DataSource.LoadAllData();

            RemoveExtendedSplash();
        }

        private async Task InstallDatabase()
        {
            StorageFile seedFile = await StorageFile.GetFileFromPathAsync(Path.Combine(Windows.ApplicationModel.Package.Current.InstalledLocation.Path, "Data\\StudentLive.sqlite"));
            await seedFile.CopyAsync(Windows.Storage.ApplicationData.Current.LocalFolder, seedFile.Name, NameCollisionOption.ReplaceExisting);

            await Task.Run(() =>
            {
                for (double i = 0; i < 99999999; i++)
                { }
            });

            
            var localSettings = Windows.Storage.ApplicationData.Current.LocalSettings;
            localSettings.Values[Constants.IsDatabaseInstalled] = true;

        }


        internal void onSplashScreenDismissed(Windows.ApplicationModel.Activation.SplashScreen sender, object e)
        {
            // The splash screen has been dismissed and the extended splash screen is now in view.
            //...

        }

        async void RemoveExtendedSplash()
        {
            await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
            {
                rootFrame.Navigate(typeof(HubPage), "AllHubGroups");
                Window.Current.Content = rootFrame;
                // TODO LINE
                ;
            });
        }
    }
}
